package com.engine.workflow.autolink.web;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.webservices.WorkflowServiceImpl;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dusongsong
 * @date 2023年05月12日 14:20
 */
public class WfUtil extends BaseBean {

    /**
     * 校验workflowId
     *
     * @param workflowId
     * @return
     */
    public Map<String, Object> checkReqParams(String workflowId, String requestName, String mainData, String isnextFlow) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        writeLog(">>>>>checkReqParams>>>workflowId=" + workflowId);
        writeLog(">>>>>checkReqParams>>>requestName=" + requestName);
        writeLog(">>>>>checkReqParams>>>mainData=" + mainData);
        writeLog(">>>>>checkReqParams>>>isnextFlow=" + isnextFlow);
        String code = "SUCCESS";
        String message = "";
        if ("".equals(workflowId.trim())) {
            code = "PARAM_ERROR";
            message += "workflowId参数必填;";
        }
        if ("".equals(Util.null2String(requestName))) {
            code = "PARAM_ERROR";
            message += "requestName参数必填;";
        }
        if ("".equals(Util.null2String(mainData))) {
            code = "PARAM_ERROR";
            message += "mainData参数必填;";
        }
        if ("".equals(Util.null2String(isnextFlow))) {
            code = "PARAM_ERROR";
            message += "isnextFlow参数必填;";
        }

        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 校验workflowId
     *
     * @param workflowId
     * @return
     */
    public Map<String, Object> checkReqParams1(String requestId, String workflowId, String isLeave) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        writeLog(">>>>>checkReqParams>>>requestId=" + requestId);
        writeLog(">>>>>checkReqParams>>>workflowId=" + workflowId);
        writeLog(">>>>>checkReqParams>>>isLeave=" + isLeave);
        String code = "SUCCESS";
        String message = "";
        if ("".equals(workflowId.trim())) {
            code = "PARAM_ERROR";
            message += "requestId参数必填;";
        }
        if ("".equals(Util.null2String(workflowId))) {
            code = "PARAM_ERROR";
            message += "workflowId参数必填;";
        }
        if ("".equals(Util.null2String(isLeave))) {
            code = "PARAM_ERROR";
            message += "isLeave参数必填;";
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 校验token
     *
     * @param encrypttoken
     * @return
     */
    public Map<String, Object> checkHeadParams(String encrypttoken, String encryptUserid) {
        writeLog(">>>>>checkHeadParams>>>RASUserid=" + encrypttoken);
        writeLog(">>>>>checkHeadParams>>>RASToken=" + encryptUserid);
        boolean hasToken = getToken();
        writeLog(">>>>>checkToken>>>>>hasToken" + hasToken);
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String code = "SUCCESS";
        String message = "";
        if("".equals(encrypttoken) || !hasToken){
            code = "HEAD_PARAM_ERROR";
            message = "token不存在或者超时:" + encrypttoken;
        } else {
            try {
                String decUserid = Util.null2String(getDecryptStr(encryptUserid));
                ResourceComInfo resourceComInfo = new ResourceComInfo();
                String loginid = Util.null2String(resourceComInfo.getLoginID(decUserid));
                if (!"".equals(loginid)) {
                    code = "SUCCESS";
                    message = decUserid;
                } else {
                    code = "HEAD_PARAM_ERROR";
                    message = "人员ID不存在:" + decUserid;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 私钥解密
     *
     * @param
     * @return
     */
    public boolean getToken() {
        RecordSet rs = new RecordSet();
        //String appid = "EEAA5436-7577-4BE0-8C6C-89E9D888";
        boolean flag = true;
        String appid = "weaver";
        String fullDate = DateUtil.getFullDate();
        rs.executeQuery("select expire_time from ecology_mobile_token where msg='\"" + appid + "\"'");
        rs.next();
        String expireTime = Util.null2String(rs.getString(1));
        writeLog("expireTime=" + expireTime);
        if ("".equals(expireTime)) {
            flag = false;
        }else {
            Date dat1 = DateUtil.parseToDate(fullDate,"yyyy-MM-dd hh:mm:ss");
            Date dat2 = DateUtil.parseToDate(expireTime,"yyyy-MM-dd hh:mm:ss");
            if(dat1.after(dat2)){
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 提交流程
     */
    public String submitWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.submitWorkflowRequest(null, requestid, userid, "submit", "由外部调用提交完成");
    }
    /**
     * 删除流程
     */
    public boolean deleteWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.deleteRequest(Util.getIntValue(requestid), Util.getIntValue(userid));
    }
    /**
     * @param @param  creatorId    创建人Id
     * @param @param  workflowId   流程Id
     * @param @param  requestName  请求标题
     * @param @param  IsNextFlow   是否提交到下一节点
     * @param @param  requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: WorkflowCreateByMainTableMap
     */
    public String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, Object> requestMainMap) {
        writeLog( "-----创建流程传递的参数个数--------" );
        writeLog( "creatorId:" + creatorId );
        writeLog( "workflowId:" + workflowId );
        writeLog( "requestName:" + requestName );
        writeLog( "IsNextFlow:" + IsNextFlow );

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid( creatorId );//创建人Id
        requestInfo.setWorkflowid( workflowId );//工作流Id
        requestInfo.setDescription( requestName );//请求标题
        if ("0".equals( IsNextFlow )) {
            requestInfo.setIsNextFlow( IsNextFlow );
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, Object> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName( Util.null2String( entry.getKey() ) );
            propertyArray[p].setValue( Util.null2String( entry.getValue() ) );
            writeLog( "\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue() );
            p++;
        }
        writeLog( "-----创建流程传递的参数个数p=" + p );
        mainTableInfo.setProperty( propertyArray );
        requestInfo.setMainTableInfo( mainTableInfo );
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest( requestInfo );//创建请求id
            } catch (Exception e) {
                writeLog( "=======" + e.getMessage() );
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer( "\r\n-----xwd创建工作流记录日志开始" );
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append( "\r\n-----姓名:" + rscif.getLastname( rcif.getRequestCreater( requestid ) ) );
            sbf.append( "\r\n-----时间:" + rcif.getRequestCreateTime( requestid ) );
            sbf.append( "\r\n-----创建流程:" + wfcif.getWorkflowname( workflowId ) );
            sbf.append( "\r\n-----请求:" + rcif.getRequestname( requestid ) );
            sbf.append( "\r\n-----请求:" + requestid );
            sbf.append( "\r\n-----创建工作流记录日志结束" );
            writeLog( sbf.toString() );
            System.out.println( "" + sbf.toString() );
        } catch (Exception e) {
            writeLog( "错误：" + e );
            System.out.println( "错误：" + e );
        }
        return requestid;
    }

    /**
     * 更新主表表单信息
     */
    public boolean updateMainData(String tablename, String requestid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        //遍历数据 进行update
        String updatesql = "update " + tablename + " set ";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            updatesql += key + "='" + map.get(key).toString() + "',";
        }
        if (updatesql.endsWith(",")) {
            updatesql = updatesql.substring(0, updatesql.length() - 1);
            updatesql += " where requestid=" + requestid;
        }
        writeLog(">>>>>updateMainData>>>>updatesql=" + updatesql);
        return rs.executeUpdate(updatesql);
    }

    /**
     * 更新明细表单信息
     */
    public boolean updateDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>updateDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 删除明细表数据
     */
    public boolean deleteDetailData(String tableName, String mainid) {
        RecordSet rs = new RecordSet();
        return rs.executeUpdate("delete from  " + tableName + " where mainid=?", mainid);
    }

    /**
     * 获取明细主键ID
     */
    public String getIdByRequestId(String workflowid, String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select abs(formid) from  workflow_base where id=?", workflowid);
        rs.next();
        String tableName = "formtable_main_"+ Util.null2String(rs.getString(1));
        rs.executeQuery("select id from " + tableName + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 私钥解密
     *
     * @param encryptStr
     * @return
     */
    public String getDecryptStr(String encryptStr) {
        RecordSet rs = new RecordSet();
        //String appid = "EEAA5436-7577-4BE0-8C6C-89E9D888";
        String appid = "weaver";
        String decryptStr = "";
        try {
            rs.executeQuery("select RSA_PRV from ECOLOGY_BIZ_EC where appid=?", appid);
            rs.next();
            String prv = Util.null2String(rs.getString(1));
            writeLog("prv=" + prv);
            RSA rsa = new RSA(prv, null);
            decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptStr;
    }

}
